package com.dm.learn.java.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {
	public static Semaphore semaphore1 = new Semaphore(0);
	private static Semaphore semaphore2 = new Semaphore(0);
	private static Semaphore semaphore3 = new Semaphore(0);
	public Thread t1;
	public Thread t2;
	public Thread t3;
	int count = 10;

	public SemaphoreTest() {
		t1 = new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				semaphore3.release();
				int i = 0;
				while (i++ < count) {
					try {
						semaphore3.acquire();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.print("A");
					semaphore1.release();
				}
				super.run();
			}

		};
		t2 = new Thread() {
			public void run() {
				try {
					int i = 0;
					while (i++ < count) {
						semaphore1.acquire();
						System.out.print("B");
						semaphore2.release();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		t3 = new Thread() {
			public void run() {
				try {
					int i = 0;
					while (i++ < count) {
						semaphore2.acquire();
						System.out.print("C");
						semaphore3.release();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
	}

	public void runTest1() {
		t1.start();
		t2.start();
		t3.start();
	}

	public void runTest2() {
		// 线程池
		ExecutorService exec = Executors.newCachedThreadPool();
		// 只能3个线程同时访问
		final Semaphore semp = new Semaphore(3, true);
		// 模拟30个客户端访问
		for (int index = 0; index < 30; index++) {
			final int NO = index;
			Runnable run = new Runnable() {
				public void run() {
					try {
						// 获取许可
						semp.acquire();
						System.out.println("Accessing: " + NO);
						Thread.sleep(1000);
						// 访问完后，释放 ，如果屏蔽下面的语句，则在控制台只能打印5条记录，之后线程一直阻塞
						semp.release();
					} catch (InterruptedException e) {
					}
				}
			};
			exec.execute(run);
		}
		// 退出线程池
		exec.shutdown();
	}

	public static void main(String args[]) throws Exception {
		SemaphoreTest t = new SemaphoreTest();
		t.runTest1();
		// t.runTest2();

	}
}
